<script setup lang="ts">
import { Search, Refresh, CirclePlus, Download, Edit, DataLine } from "@element-plus/icons-vue"
import { deleteSourceDataApi, downloadSourceApi, getSourceDataApi } from "@/api/resources/source/index"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import { FormTypeEnum } from "@/constants/other-keys"
import { reactive, ref, watch, nextTick } from "vue"
import { SourceTableData, TableRequestData } from "@/api/resources/source/types/source"
import { SourceEdit } from "../components"
import DataAccess from "../components/source/data-access.vue"

const loading = ref<boolean>(false)
const searchMore = ref<boolean>(false)
const searchData = reactive<TableRequestData>({
  raw_data_name: undefined,
  raw_data_tag: undefined,
  raw_data_format: undefined,
  publish_time: undefined,
  end_time: undefined
})
const dialogType = ref<FormTypeEnum>(FormTypeEnum.CREATE)
const editDialogRef = ref()
const dataAccessRef = ref()
const curId = ref<string>()
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const handleSearchMore = () => {
  searchData.publish_time = undefined
  searchData.end_time = undefined
  searchMore.value = !searchMore.value
}

const dialogVisible = ref(false)

//#region 详情
const handleView = (row: SourceTableData) => {
  nextTick(() => {
    curId.value = row.raw_data_id
    dialogType.value = FormTypeEnum.VIEW
    dialogVisible.value = true
  })
}
//#endregion
//#region 增
const handleCreate = () => {
  nextTick(() => {
    curId.value = undefined
    dialogType.value = FormTypeEnum.CREATE
    dialogVisible.value = true
  })
}
//#endregion
//#region 删
const handleDelete = (row: SourceTableData) => {
  ElMessageBox.confirm(`正在删除：${row.raw_data_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteSourceDataApi(row.raw_data_id).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
// const handleUpdate = (row: SourceTableData) => {
//   nextTick(() => {
//     dialogType.value = FormTypeEnum.EDIT
//     curId.value = row.raw_data_id
//     dialogVisible.value = true
//   })
// }
//#endregion
//#region 查
const tableData = ref<SourceTableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const getTableData = () => {
  loading.value = true
  parent &&
    getSourceDataApi({
      size: paginationData.pageSize,
      current_page: paginationData.currentPage,
      raw_data_name: searchData.raw_data_name,
      raw_data_tag: searchData.raw_data_tag,
      raw_data_format: searchData.raw_data_format,
      publish_time: searchData.publish_time || undefined,
      end_time: searchData.end_time || undefined
    })
      .then(({ data }) => {
        tableData.value = data.page_info
        paginationData.total = data.total_count
      })
      .catch(() => {
        tableData.value = []
      })
      .finally(() => {
        loading.value = false
      })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

//#region
const handleDownload = (row: SourceTableData) => {
  downloadSourceApi(row.raw_data_id).then((res) => {
    const blob = new Blob([res.data])
    const contentPosition = res.headers["content-disposition"]
    if (contentPosition) {
      const match = contentPosition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      const fileName = match[1].replace(/['"]/g, "")
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a")
        elink.download = fileName
        elink.style.display = "none"
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }
    } else {
      ElMessage.error("下载失败")
    }
  })
}
//#endregion

const closeDialog = (param: string | undefined) => {
  dialogVisible.value = false
  if (param && param == "refresh") getTableData()
}
const handleOpenAnylabeling = () => {
  window.location.href = "X-AnyLabeling-CPU://"
}

//#region
const dataDialogVisible = ref(false)
// 数据接入
const handleDataAccess = () => {
  dataDialogVisible.value = true
}
const closeDataDialog = (param: string | undefined) => {
  dataDialogVisible.value = false
  if (param && param == "refresh") getTableData()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container" shadow="never">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="raw_data_name" label="名称">
          <el-input v-model="searchData.raw_data_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="raw_data_tag" label="标签">
          <el-input v-model="searchData.raw_data_tag" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="raw_data_format" label="数据格式">
          <el-input v-model="searchData.raw_data_format" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button link type="primary" @click="handleSearchMore">{{ searchMore ? "收起" : "更多" }}</el-button>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-row v-if="searchMore">
          <el-form-item prop="publish_time" label="发布时间">
            <el-date-picker
              v-model="searchData.publish_time"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item prop="end_time" label="截至时间">
            <el-date-picker v-model="searchData.end_time" value-format="YYYY-MM-DD" type="date" placeholder="请选择" />
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <div class="toolbar-wrapper">
      <div>
        <el-button type="primary" :icon="CirclePlus" @click="handleCreate">数据上传</el-button>
        <el-button type="primary" :icon="DataLine" @click="handleDataAccess">数据接入</el-button>
        <el-button type="primary" :icon="Edit" @click="handleOpenAnylabeling">标签制作</el-button>
      </div>
    </div>
    <el-row v-loading="loading" shadow="never" :gutter="20">
      <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="5" class="mb-5" v-for="(item, index) in tableData" :key="index">
        <el-card class="card-item" body-class="card-item body">
          <template #header>
            <div class="card-header flex-between">
              <el-space class="flex-vc">
                <el-icon><Calendar /></el-icon>
                <el-text>{{ item.create_time }}</el-text>
              </el-space>
              <el-link :underline="false" v-throttle="() => handleDownload(item)">
                <el-icon :size="18"><Download /></el-icon>
              </el-link>
            </div>
          </template>
          <div class="card-body">
            <div class="flex-between relation">
              <el-space class="flex-vc">
                <el-text size="large" class="w-150px mb-2" truncated>
                  {{ item.raw_data_name }}
                </el-text>
              </el-space>
              <el-space class="flex-vc card-operate">
                <el-link :underline="false" @click="handleView(item)">
                  <el-icon :size="18"><View /></el-icon>
                </el-link>
                <!-- <el-link :underline="false" @click="handleUpdate(item)">
                  <el-icon :size="18"><Edit /></el-icon>
                </el-link> -->
                <el-link :underline="false" @click="handleDelete(item)">
                  <el-icon :size="18"><Delete /></el-icon>
                </el-link>
              </el-space>
            </div>
            <p class="describe">
              <el-text type="info" line-clamp="2">
                {{ item.raw_data_describe }}
              </el-text>
            </p>
          </div>
          <template #footer>
            <div class="card-footer flex-between">
              <el-space class="flex-vc">
                <el-icon><UserFilled /></el-icon>
                <el-text>{{ item.create_user.user_name }}</el-text>
              </el-space>
              <el-tag type="info" effect="plain">{{ item.create_user.user_position }}</el-tag>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>
    <div class="pager-wrapper">
      <el-pagination
        background
        :layout="paginationData.layout"
        :page-sizes="paginationData.pageSizes"
        :total="paginationData.total"
        :page-size="paginationData.pageSize"
        :currentPage="paginationData.currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <SourceEdit
      ref="editDialogRef"
      :id="curId"
      :dialog-type="dialogType"
      :visible="dialogVisible"
      @closeDialog="closeDialog"
    />
    <DataAccess ref="dataAccessRef" :visible="dataDialogVisible" @closeDialog="closeDataDialog" />
  </div>
</template>
<style lang="scss" scoped>
@import "@/styles/custom.scss";
</style>
